package cn.virens.web.controller;

import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.ThreadLocalRandom;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.RandomUtil;
import cn.virens.common.CloseableUtil;
import cn.virens.web.common.BaseJSONController;

@Controller
public class CaptchaContorller extends BaseJSONController {
	private static final ThreadLocalRandom random = RandomUtil.getRandom();
	private static final int interfereCount = 15;
	private static final int codeCount = 4;
	private static final int height = 100;
	private static final int width = 200;

	@ResponseBody
	@RequestMapping("/login/captcha.png")
	public byte[] captcha(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		ByteArrayOutputStream outputStream = null;
		try {
			// 1.创建验证码规则
			final String captcha = RandomUtil.randomString(codeCount);
			final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			final Graphics2D graphics = ImgUtil.createGraphics(image, ImgUtil.randomColor(random));

			// 2.创建字体
			graphics.setFont(new Font("Courier", Font.PLAIN, height - 2));

			// 3.绘制干扰线
			for (int i = 0; i < interfereCount; i++) {
				int xs = random.nextInt(width);
				int ys = random.nextInt(height);
				int xe = xs + random.nextInt(width / 8);
				int ye = ys + random.nextInt(height / 8);

				graphics.setColor(ImgUtil.randomColor(random));
				graphics.drawLine(xs, ys, xe, ye);
			}

			// 4.绘制文字
			int charWidth = width / (codeCount + 2);
			for (int i = 0; i < codeCount; i++) {
				String c = String.valueOf(captcha.charAt(i));
				int x = i * charWidth + (charWidth >> 1);
				int y = RandomUtil.randomInt(height >> 1) + (height >> 1);

				// 产生随机的颜色值，让输出的每个字符的颜色值都将不同。
				graphics.setColor(ImgUtil.randomColor(random));
				graphics.drawString(c, x, y);
			}

			// 5.将验证码转为byte数组
			ImageIO.write(image, "png", (outputStream = new ByteArrayOutputStream()));// 输出到文件流

			// 6.将验证码存入session
			HttpSession session = getSession(request);

			session.setAttribute("captcha", captcha);
			session.setAttribute("captcha_time", System.currentTimeMillis());

			// 7.设置图片响应头
			response.setContentLength(outputStream.size());
			response.setContentType(MediaType.IMAGE_PNG_VALUE);

			// 8.返回图片byte[]
			return outputStream.toByteArray();
		} finally {
			CloseableUtil.close(outputStream);
		}
	}

	@ResponseBody
	@RequestMapping("/login/captcha/value.json")
	public Model captchaJson(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
		model.addAttribute("captcha_time", getAttribute(request, "captcha.time", Long.class));
		model.addAttribute("captcha", getAttribute(request, "captcha", String.class));

		return model;
	}
}
